package repository

import (
	"context"
	"database/sql"
	"fmt"
	"strings"

	"mall/common/modelx"
	"mall/service/attachment/model"

	"github.com/volatiletech/sqlboiler/v4/boil"
	"github.com/volatiletech/sqlboiler/v4/queries/qm"
	"github.com/zeromicro/go-zero/core/stores/cache"
)

type (
	// AttachmentRepository is an interface to be customized, add more methods here,
	// and implement the added methods in customAttachmentRepository.
	AttachmentRepository interface {
		Conn() error
		FindOne(ctx context.Context, id int64, cols []string) (*model.Attachment, error) /////
		GetList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]interface{},
		) ([]*model.Attachment, int64, error) /////
		Insert(
			ctx context.Context,
			attachment *model.Attachment,
			extra *model.AttachmentExtra,
		) error /////
		Update(
			ctx context.Context,
			attachment *model.Attachment,
			extra *model.AttachmentExtra,
		) (int64, error) /////
		UpdateBatch(ctx context.Context, ids []int64, cols model.M) (int64, error)
		ForceDeleteBatch(ctx context.Context, ids []int64) (int64, error)
		GetMeta(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]interface{},
		) ([]*model.AttachmentMetum, int64, error) /////
	}

	customAttachmentRepository struct {
		cacheConf  cache.CacheConf
		dataSource string

		mysqlConn *sql.DB
	}
)

// NewAttachmentRepository returns a repository for the database table.
func NewAttachmentRepository(dataSource string, cacheConf cache.CacheConf) AttachmentRepository {
	return &customAttachmentRepository{
		cacheConf:  cacheConf,
		dataSource: dataSource,
	}
}

func (r *customAttachmentRepository) Conn() error {
	if r.mysqlConn == nil {
		mysqlConn, err := modelx.NewMysqlConn(r.dataSource)
		if err != nil {
			return err
		}

		r.mysqlConn = mysqlConn
	}

	return nil
}

func (r *customAttachmentRepository) FindOne(
	ctx context.Context,
	id int64,
	cols []string,
) (attachment *model.Attachment, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	attachment, err = model.FindAttachment(ctx, r.mysqlConn, uint64(id), cols...)
	return
}

func (r *customAttachmentRepository) GetList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]interface{},
) (list []*model.Attachment, count int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	var mods []qm.QueryMod
	var page int
	var pageSize int
	var offset int
	var limit int
	var selectCol string
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(int64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(int64); ok && val > 0 {
				pageSize = int(val)
			}
		case "offset":
			if val, ok := v.(int32); ok && val > 0 {
				offset = int(val)
			}
		case "limit":
			if val, ok := v.(int32); ok && val > 0 {
				limit = int(val)
			}
		case "orderBy":
			if val, ok := v.(string); ok && val != "" {
				mods = append(mods, qm.OrderBy(val))
			}
		case "select":
			if val, ok := v.(string); ok && val != "" {
				selectCol = val
			}
		case "search":
			if val, ok := v.(string); ok && val != "" { // 搜索
				likeVal := fmt.Sprintf("%%%s%%", val)
				mods = append(mods, qm.Where(fmt.Sprintf(
					"(%s LIKE ? OR %s LIKE ?)",
					model.AttachmentColumns.PostTitle,
					model.AttachmentColumns.PostExcerpt), likeVal, likeVal))
			}
		}
	}

	if filter != nil {
		for key, opMap := range filter {
			switch key {
			case model.AttachmentColumns.ID:
				mods = append(mods, modelx.GetIntMods(model.AttachmentColumns.ID, opMap)...)
			case model.AttachmentColumns.PostAuthorID:
				mods = append(mods, modelx.GetIntMods(model.AttachmentColumns.PostAuthorID, opMap)...)
			case model.AttachmentColumns.PostParentID:
				mods = append(mods, modelx.GetIntMods(model.AttachmentColumns.PostParentID, opMap)...)
			case model.AttachmentColumns.PostTitle:
				mods = append(mods, modelx.GetStringMods(model.AttachmentColumns.PostTitle, opMap)...)
			case model.AttachmentColumns.PostExcerpt:
				mods = append(mods, modelx.GetStringMods(model.AttachmentColumns.PostExcerpt, opMap)...)
			case model.AttachmentColumns.PostStatus:
				mods = append(mods, modelx.GetIntMods(model.AttachmentColumns.PostStatus, opMap)...)
			case model.AttachmentColumns.CommentStatus:
				mods = append(mods, modelx.GetIntMods(model.AttachmentColumns.CommentStatus, opMap)...)
			case model.AttachmentColumns.PostName:
				mods = append(mods, modelx.GetStringMods(model.AttachmentColumns.PostName, opMap)...)
			case model.AttachmentColumns.PostType:
				mods = append(mods, modelx.GetIntMods(model.AttachmentColumns.PostType, opMap)...)
			}
		}
	}

	if withCount >= 0 {
		if withCount == 2 {
			var nextCount int64
			var previousCount int64
			subMods := make([]qm.QueryMod, len(mods), len(mods) + 3)
			copy(subMods, mods)
			subMods = append(subMods, qm.Limit(1))
			subMods = append(subMods, qm.Select(model.AttachmentColumns.ID))

			if offset >= 1 {
				subMods = append(subMods, qm.Offset(offset - 1))
				previousList, previousErr := model.Attachments(subMods...).All(ctx, r.mysqlConn)
				if previousErr != nil {
					err = previousErr
					return
				}
				if len(previousList) > 0 {
					previousCount = 1
				}
			}
			if limit > 0 {
				subMods = append(subMods, qm.Offset(offset + limit))
				nextList, nextErr := model.Attachments(subMods...).All(ctx, r.mysqlConn)
				if nextErr != nil {
					err = nextErr
					return
				}
				if len(nextList) > 0 {
					nextCount = 1
				}
			}

			count = previousCount + nextCount * 2
		} else {
			count, err = model.Attachments(mods...).Count(ctx, r.mysqlConn)
			if err != nil {
				return
			}

			if withCount == 0 {
				return
			}
		}
	}

	if pageSize > 0 {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	} else if limit > 0 || offset > 0 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit))
		}
		if offset > 0 {
			mods = append(mods, qm.Offset(offset))
		}
	}

	var columns []string
	if selectCol != "" {
		if selectCol != "," {
			columns = strings.Split(selectCol, ",")
		}
		columns = append(columns, model.AttachmentColumns.ID)
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.Attachments(mods...).All(ctx, r.mysqlConn)
	return
}

func (r *customAttachmentRepository) Insert(
	ctx context.Context,
	attachment *model.Attachment,
	extra *model.AttachmentExtra,
) error {
	if err := r.Conn(); err != nil {
		return err
	}

	tx, err := r.mysqlConn.BeginTx(ctx, nil)
	if err != nil {
		return err
	}

	err = attachment.Insert(ctx, tx, boil.Infer())
	if err != nil {
		tx.Rollback()
		return err
	}

	if extra != nil {
		aid := attachment.ID

		if len(extra.Meta) > 0 {
			for _, m := range extra.Meta {
				m.AttachmentID = aid
				err = m.Insert(ctx, tx, boil.Infer())
				if err != nil {
					tx.Rollback()
					return err
				}
			}
		}
		if len(extra.CategoryIds) > 0 {
			for _, cid := range extra.CategoryIds {
				var relationShip model.AttachmentTermRelationship
				relationShip.ObjectID = aid
				relationShip.TermID = uint64(cid)
				err = relationShip.Insert(ctx, tx, boil.Infer())
				if err != nil {
					tx.Rollback()
					return err
				}
			}
		}
		if len(extra.TagIds) > 0 {
			for _, tid := range extra.TagIds {
				var relationShip model.AttachmentTermRelationship
				relationShip.ObjectID = aid
				relationShip.TermID = uint64(tid)
				err = relationShip.Insert(ctx, tx, boil.Infer())
				if err != nil {
					tx.Rollback()
					return err
				}
			}
		}
	}

	tx.Commit()
	return nil
}

func (r *customAttachmentRepository) Update(
	ctx context.Context,
	attachment *model.Attachment,
	extra *model.AttachmentExtra,
) (int64, error) {
	if err := r.Conn(); err != nil {
		return 0, err
	}

	tx, err := r.mysqlConn.BeginTx(ctx, nil)
	if err != nil {
		return 0, err
	}

	attachmentId, err := attachment.Update(ctx, tx, boil.Blacklist(
		model.AttachmentColumns.PostAuthorID,
		model.AttachmentColumns.PostDate,
		model.AttachmentColumns.PostDateGMT,
		model.AttachmentColumns.CommentCount,
	))
	if err != nil {
		tx.Rollback()
		return 0, err
	}

	if extra != nil {
		aid := attachment.ID

		if len(extra.Meta) > 0 {
			for _, m := range extra.Meta {
				if m.MetaID > 0 {
					_, err = m.Update(ctx, tx, boil.Blacklist(
						model.AttachmentMetumColumns.MetaID,
						model.AttachmentMetumColumns.AttachmentID,
					))
				} else {
					m.AttachmentID = aid
					err = m.Insert(ctx, tx, boil.Infer())
				}

				if err != nil {
					tx.Rollback()
					return 0, err
				}
			}
		}
		if len(extra.CategoryIds) > 0 {
			for _, cid := range extra.CategoryIds {
				var relationShip model.AttachmentTermRelationship
				relationShip.ObjectID = aid
				relationShip.TermID = uint64(cid)
				err = relationShip.Insert(ctx, tx, boil.Infer())
				if err != nil {
					tx.Rollback()
					return 0, err
				}
			}
		}
		if len(extra.TagIds) > 0 {
			for _, tid := range extra.TagIds {
				var relationShip model.AttachmentTermRelationship
				relationShip.ObjectID = aid
				relationShip.TermID = uint64(tid)
				err = relationShip.Insert(ctx, tx, boil.Infer())
				if err != nil {
					tx.Rollback()
					return 0, err
				}
			}
		}
		if len(extra.DelTermIds) > 0 {
			ids := make([]interface{}, 0, len(extra.DelTermIds))
			for _, id := range extra.DelTermIds {
				ids = append(ids, id)
			}
			var mods []qm.QueryMod
			mods = append(mods, model.AttachmentTermRelationshipWhere.ObjectID.EQ(aid))
			mods = append(mods, qm.WhereIn(fmt.Sprintf("%s IN ?", model.AttachmentTermRelationshipColumns.TermID), ids...))
			_, err := model.AttachmentTermRelationships(mods...).DeleteAll(ctx, tx)
			if err != nil {
				tx.Rollback()
				return 0, err
			}
		}
		if len(extra.DelMetaIds) > 0 {
			ids := make([]interface{}, 0, len(extra.DelMetaIds))
			for _, id := range extra.DelMetaIds {
				ids = append(ids, id)
			}
			var mods []qm.QueryMod
			mods = append(mods, qm.WhereIn(fmt.Sprintf("%s IN ?", model.AttachmentMetumColumns.MetaID), ids...))
			_, err := model.AttachmentMeta(mods...).DeleteAll(ctx, tx)
			if err != nil {
				tx.Rollback()
				return 0, err
			}
		}
	}

	tx.Commit()
	return attachmentId, nil
}

func (r *customAttachmentRepository) UpdateBatch(ctx context.Context, ids []int64, cols model.M) (rowsAff int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	var mods []qm.QueryMod
	if len(ids) > 0 {
		values := make([]interface{}, 0, len(ids))
		for _, id := range ids {
			values = append(values, uint64(id))
		}

		mods = append(mods, qm.WhereIn(fmt.Sprintf("%s IN ?", model.AttachmentColumns.ID), values...))
	}

	rowsAff, err = model.Attachments(mods...).UpdateAll(ctx, r.mysqlConn, cols)
	return
}

func (r *customAttachmentRepository) ForceDeleteBatch(ctx context.Context, ids []int64) (rowsAff int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	var mods []qm.QueryMod
	if len(ids) > 0 {
		values := make([]interface{}, 0, len(ids))
		for _, id := range ids {
			values = append(values, uint64(id))
		}

		mods = append(mods, qm.WhereIn(fmt.Sprintf("%s IN ?", model.AttachmentColumns.ID), values...))
	}

	rowsAff, err = model.Attachments(mods...).DeleteAll(ctx, r.mysqlConn)
	return
}

func (r *customAttachmentRepository) GetMeta(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]interface{},
) (list []*model.AttachmentMetum, count int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	var mods []qm.QueryMod
	var page int
	var pageSize int
	var selectCol string
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(int64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(int64); ok && val > 0 {
				pageSize = int(val)
			}
		case "orderBy":
			if val, ok := v.(string); ok && val != "" {
				mods = append(mods, qm.OrderBy(val))
			}
		case "select":
			if val, ok := v.(string); ok && val != "" {
				selectCol = val
			}
		}
	}

	if filter != nil {
		for key, opMap := range filter {
			switch key {
			case model.AttachmentMetumColumns.MetaID:
				mods = append(mods, modelx.GetIntMods(model.AttachmentMetumColumns.MetaID, opMap)...)
			case model.AttachmentMetumColumns.AttachmentID:
				mods = append(mods, modelx.GetIntMods(model.AttachmentMetumColumns.AttachmentID, opMap)...)
			case model.AttachmentMetumColumns.MetaKey:
				mods = append(mods, modelx.GetStringMods(model.AttachmentMetumColumns.MetaKey, opMap)...)
			}
		}
	}

	if withCount >= 0 {
		count, err = model.AttachmentMeta(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if selectCol != "" {
		if selectCol != "," {
			columns = strings.Split(selectCol, ",")
		}
		columns = append(columns, model.AttachmentMetumColumns.MetaID)
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.AttachmentMeta(mods...).All(ctx, r.mysqlConn)
	return
}
